package com.dcloud.file.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dcloud.file.service.FileService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/api/uploadfile/v1")
@Slf4j
public class FileController {
    @Resource(name = "localFileService")
    private FileService fileService;

    @PostMapping("/upload")
    public Result<?> upload(@RequestParam("file") MultipartFile file) {
        try {
            return fileService.upload(file);
        } catch (Exception e) {
            return Result.ok("上传失败");
        }
    }


    @AutoLog(value = "文件下载")
    @ApiOperation(value="文件下载", notes="文件下载")
    @RequestMapping(value = "/download/{fileName}",method = RequestMethod.GET)
    public void download(@PathVariable("fileName") String fileName, HttpServletResponse response) {

        try {
            ServletOutputStream outputStream = response.getOutputStream();
            InputStream inputStream =  fileService.getFile(fileName);
            response.addHeader("Content-Disposition",
                    "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] b = new byte[1024];
            int len;
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            inputStream.close();
            outputStream.close();
        } catch (Exception ex) {
            log.error("download is error ", ex);
        }
    }




}
